import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import sample.utils.ExcelUtil;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class AdressParser {

    private static List<String> filter = Arrays.asList("市辖区");

    private static JSONObject excel2Json(){
        File file = new File("test/AMap_adcode_citycode.xlsx");
        List<List<String>> list = ExcelUtil.readExcel(file, 0 ,2);

        JSONObject json = new JSONObject();
        List<Address> province = Lists.newArrayList();
        List<Address> city = Lists.newArrayList();
        List<Address> district = Lists.newArrayList();

        Address address = null;
        for (List<String> row: list) {
            String name = row.get(0);
            String code = row.get(1);

            address = new Address(code, name);

            if(code.endsWith("0000")) {
                province.add(address);
            } else if(code.endsWith("00")) {
                if(name.contains("市辖区")) {
                    name = name .replaceAll("市辖区","");
                    address.setName(name);
                }
                city.add(address);
            } else {
                if(name.contains("市辖区")) {
                    continue;
                }
                district.add(address);
            }
        }

        json.put("province", province);

        province.stream().forEach(p->{
            String pCode = p.getCode();

            List<Address> citys = city.stream().filter(x->x.getCode().startsWith(pCode.substring(0,2))).collect(Collectors.toList());
            json.put(p.getCode(), citys);
        });

        city.stream().forEach(c->{
            String pCode = c.getCode();

            List<Address> citys = district.stream().filter(x->x.getCode().startsWith(pCode.substring(0,4))).collect(Collectors.toList());
            json.put(c.getCode(), citys);
        });

        return json;
    }

    public static void main(String[] args) throws IOException {
       System.out.println(excel2Json());
       // jsonFileToObject();
    }

    private static void jsonFileToObject() throws IOException {



    }
}
